"""
decorators.py

Decorators for URL handlers

"""

from functools import wraps
from google.appengine.api import users
from flask import redirect, request, url_for, flash
from application import app
from application.models import Character

def login_required(func):
	"""Requires standard login credentials"""
	@wraps(func)
	def decorated_view(*args, **kwargs):
		if not users.get_current_user():
			return redirect(users.create_login_url(request.url))
		return func(*args, **kwargs)
	return decorated_view


def admin_required(func):
	"""Requires App Engine admin credentials"""
	@wraps(func)
	def decorated_view(*args, **kwargs):
		if not users.is_current_user_admin():
			return redirect(users.create_login_url(request.url))
		return func(*args, **kwargs)
	return decorated_view

def template_init(func):
	"""Requires template to be initialised"""
	@wraps(func)
	def decorated_view(*args, **kwargs):
		user = users.get_current_user()
		if user:
			app.jinja_env.globals['user'] = user
			app.jinja_env.globals['userLogoutUrl'] = users.create_logout_url(url_for("home"))
			app.jinja_env.globals['userAdmin'] = users.is_current_user_admin()
			characters = Character.getUsersCharacters(user)
			app.jinja_env.globals['characters'] = characters
			if len(characters) == 0:
				flash('You do not have any characters registered. Please <a href="%s">add a character</a>.' % '/characters/add')
		else:
			app.jinja_env.globals['user'] = None
			app.jinja_env.globals['userLoginUrl'] = users.create_login_url(request.url)
			app.jinja_env.globals['userAdmin'] = False
		return func(*args, **kwargs)
	return decorated_view
